﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProTrack.Api.Helper;
using ProTrack.Dto;
using ProTrack.Entity;
using ProTrack.IServices.Plans;
using ProTrack.Utility;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System;
using ProTrack.IServices.ProductProcess;
using ProTrack.Report;

namespace ProTrack.Api.Controllers
{
    /// <summary>
    /// 工艺流程服务接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class ProRouteController : Controller
    {
        public ProRouteController(IProRouteServices services, LogHelper LogHelper)
        {
            Services = services;
            this.LogHelper = LogHelper;
        }
        private IProRouteServices Services { get; }
        private LogHelper LogHelper { get; }

        /// <summary>
        /// 获取所有工艺流程信息方法
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAll")]
        public async Task<IActionResult> GetAll()
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAllAsync();
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                return await Error("工艺流程-获取所有", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 根据页码，页大小，工艺路线编号，工艺路线名称，是否启用获取工艺流程信息方法
        /// </summary>
        /// <param name="PageIndex">页码</param>
        /// <param name="PageSize">页大小</param>
        /// <param name="RouteCode">工艺路线编号</param>
        /// <param name="RouteName">工艺路线名称</param>
        /// <param name="EnableFlag">是否启用</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get([FromQuery] int PageIndex, [FromQuery] int PageSize, [FromQuery] string RouteCode, [FromQuery] string RouteName, [FromQuery] string EnableFlag)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetAsync(PageIndex, PageSize, RouteCode ?? "", RouteName ?? "", EnableFlag ?? "");
                status.Data = list;
                status.Count = await Services.GetCountAsync(RouteCode, RouteName, EnableFlag);
            }
            catch (Exception ex)
            {
                return await Error("工艺流程-分页获取", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 根据工艺流程编号获取工艺组成表（工艺流程附加表）方法
        /// </summary>
        /// <param name="RouteId">工艺流程编号</param>
        /// <returns></returns>
        [HttpGet("GetProRoutebyId")]
        public async Task<IActionResult> GetProRoutebyId([FromQuery] string RouteId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetProRoutebyIdAsync(RouteId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                return await Error("工艺流程-获取工艺组成表（工艺流程附加表）", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 根据工艺流程编号获取产品制程（工艺流程附加表）方法
        /// </summary>
        /// <param name="RouteId">工艺流程编号</param>
        /// <returns></returns>
        [HttpGet("GetProRouteProductbyId")]
        public async Task<IActionResult> GetProRouteProductbyId([FromQuery] string RouteId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var list = await Services.GetProRouteProductbyIdAsync(RouteId);
                status.Data = list;
                status.Count = list.Count();
            }
            catch (Exception ex)
            {
                return await Error("工艺流程-获取产品制程（工艺流程附加表）", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 根据产品物料ID查询产品制程（工艺流程附加表）是否已经配置了工艺路线方法
        /// </summary>
        /// <param name="ItemId">产品物料ID</param>
        /// <returns></returns>
        [HttpGet("GetProRouteProductisBool")]
        public async Task<IActionResult> GetProRouteProductisBool([FromQuery] string ItemId)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var result = await Services.GetProRouteProductisBool(ItemId);
                if (result)
                {
                    status.Code = -1;
                    status.Msg = "此产品已配置了工艺路线";
                }
                else
                {
                    status.Msg = "新增成功";
                }
            }
            catch (Exception ex)
            {
                return await Error("工艺流程-查询产品制程（工艺流程附加表）是否已经配置了工艺路线", ex);
            }
            return Ok(status);
        }

        /// <summary>
        /// 新增工艺流程方法
        /// </summary>
        /// <param name="model">工艺流程模型</param>
        /// <param name="ProcessString">工艺组成表（工艺流程附加表）模型</param>
        /// <param name="ProductString">产品制程（工艺流程附加表）模型</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Add([FromForm] ProRoute model, [FromForm] string ProcessString, [FromForm] string ProductString)
        {
            var status = BaseStatus.CreateInstance();
            List<ProRouteProcess> list = new List<ProRouteProcess>();
            List<ProRouteProduct> list2 = new List<ProRouteProduct>();
            try
            {
                if (!string.IsNullOrEmpty(ProcessString))
                {
                    list = JsonConvert.DeserializeObject<List<ProRouteProcess>>(ProcessString);
                    list.ForEach(x =>
                    {
                        x.RouteId = model.Id;
                        x.Creator = User.Identity.Name;
                    });
                }
                if (!string.IsNullOrEmpty(ProductString))
                {
                    list2 = JsonConvert.DeserializeObject<List<ProRouteProduct>>(ProductString);
                    list2.ForEach(x =>
                    {
                        x.RouteId = model.Id;
                        x.Creator = User.Identity.Name;
                    });
                }

                model.Creator = HttpContext.User.Identity.Name;

                var isSuccess = await Services.AddAsync(model, list, list2);
                if (isSuccess)
                    status.Msg = "新增成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "新增失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                return await Error("工艺流程-新增", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 修改工艺流程方法
        /// </summary>
        /// <param name="model">工艺流程模型</param>
        /// <param name="ProcessString">工艺组成表（工艺流程附加表）模型</param>
        /// <param name="ProductString">产品制程（工艺流程附加表）模型</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<IActionResult> Update([FromForm] ProRoute model, [FromForm] string ProcessString, [FromForm] string ProductString)
        {
            var status = BaseStatus.CreateInstance();
            List<ProRouteProcess> list = new List<ProRouteProcess>();
            List<ProRouteProduct> list2 = new List<ProRouteProduct>();
            try
            {
                if (!string.IsNullOrEmpty(ProcessString))
                {
                    list = JsonConvert.DeserializeObject<List<ProRouteProcess>>(ProcessString);
                    list.ForEach(x =>
                    {
                        x.Creator = User.Identity.Name;
                        x.RouteId = model.Id;
                    });
                }
                if (!string.IsNullOrEmpty(ProductString))
                {
                    list2 = JsonConvert.DeserializeObject<List<ProRouteProduct>>(ProductString);
                    list2.ForEach(x =>
                    {
                        x.Creator = User.Identity.Name;
                        x.RouteId = model.Id;
                    });
                }
                model.UpdateTime = StringHelper.GetTimeNow();
                model.Updater = HttpContext.User.Identity.Name;
                var isSuccess = await Services.UpdateAsync(model, list, list2);
                if (isSuccess)
                    status.Msg = "修改成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "修改失败，请检查数据。";
                }
            }
            catch (Exception ex)
            {
                return await Error("工艺流程-修改", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 批量删除工艺流程方法
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        [HttpDelete("DelAll")]
        public async Task<IActionResult> DelAll([FromForm] string Ids)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var arr = Ids.SplitId();
                var isSuccess = await Services.DeleteAsync(arr);
                if (isSuccess)
                    status.Msg = "删除成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                return await Error("工艺流程-批量删除", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 删除工艺流程方法
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<IActionResult> Del([FromForm] int Id)
        {
            var status = BaseStatus.CreateInstance();
            try
            {
                var isSuccess = await Services.DeleteAsync(Id);
                if (isSuccess)
                    status.Msg = "删除成功";
                else
                {
                    status.Code = -1;
                    status.Msg = "删除失败，请稍后重试。";
                }
            }
            catch (Exception ex)
            {
                return await Error("工艺流程-删除", ex);
            }
            return Ok(status);
        }
        /// <summary>
        /// 导出
        /// </summary>
        /// <returns></returns>
        [HttpGet("Export")]
        public async Task<IActionResult> Export()
        {
            try
            {
                var list = await Services.GetAllAsync();
                var TitleArray = new ReportDomain[]
                {
                    new ReportDomain{Title="序号",Fileld="No"},
                    new ReportDomain{Title="工艺路线编号",Fileld="RouteCode"},
                    new ReportDomain{Title="工艺路线名称",Fileld="RouteName"},
                    new ReportDomain{Title="工艺路线说明",Fileld="RouteDesc"},
                    new ReportDomain{Title="是否启用",Fileld="EnableFlag"},
                    new ReportDomain{Title="备注",Fileld="Remark"}
                };
                var fileArray = BaseReport.Export(list, "工艺流程信息", TitleArray);
                return File(new System.IO.MemoryStream(fileArray), "application/octet-stream", "工艺流程信息.xls");
            }
            catch (Exception ex)
            {
                await LogHelper.WriteErrorLog("工艺流程-导出", ex, HttpContext);
                return new JsonResult(BaseStatus.CreateInstance(-1, "导出失败，服务器异常请稍后再试！"));
            }
        }
        /// <summary>
        /// 错误信息
        /// </summary>
        /// <param name="ExString"></param>
        /// <param name="ex"></param>
        /// <returns></returns>
        private async Task<IActionResult> Error(string ExString, Exception ex)
        {
            var status = BaseStatus.CreateInstance();
            status.Code = -1;
            status.Msg = "服务器异常，请稍后重试";
            //写日志
            await LogHelper.WriteErrorLog(ExString, ex, HttpContext);
            return new ObjectResult(status) { StatusCode = StatusCodes.Status500InternalServerError };
        }
    }
}
